import time
from PIL import ImageGrab
import cv2
from PIL import Image
import requests
import time
from array import array
import threading

autoRotate = True
useDither = False
BWThreshold = 70
outbinname = r"D:\\data\out.bin"
outimgname = r"D:\\data\out.jpg"


def grab(filenameGrab):
    img = ImageGrab.grab(bbox=(0, 0, 1920, 1080))
    img.save(filenameGrab)

############################


def size(address):
    global resizedImage
    print('[图像处理]正在处理图片: 调整大小\n')
    image = Image.open(address).convert('L')
    width = image.size[0]
    height = image.size[1]
    if(height > width and autoRotate):
        image = image.transpose(Image.ROTATE_90)
        print('[图像处理]正在处理图片: 旋转90度 \n')
    width = image.size[0]
    height = image.size[1]
    n = height/384.0
    w = int(width/n)
    h = int(height/n)
    resizedImage = image.resize((int(w), int(h)))
    #resizedImage = resizedImage.transpose(Image.FLIP_LEFT_RIGHT)


def dither(image):
    factor = 1
    if(factor < 1):
        factor = 1
    print('[图像处理]正在处理图片: Floyd-Steinberg抖动\n')
    width = image.size[0]
    height = image.size[1]
    pimgGray = image.load()
    for y in range(0, height-1):
        for x in range(1, width-1):
            oldPixel = pimgGray[x, y]
            newPixel = round(round(factor*oldPixel/255) * (255/factor))
            pimgGray[x, y] = int(newPixel)
            quantErr = oldPixel - newPixel
            pimgGray[x+1, y] += int((quantErr*7/16.0))
            pimgGray[x-1, y+1] += int((quantErr*3/16.0))
            pimgGray[x, y+1] += int((quantErr*5/16.0))
            pimgGray[x+1, y+1] += int((quantErr/16.0))


def blackwhite(image, black):
    print('[图像处理]正在处理图片: 黑白\n')
    width = image.size[0]
    height = image.size[1]
    pimgGray = image.load()
    for y in range(0, height):
        for x in range(0, width):
            if(pimgGray[x, y] > black):
                pimgGray[x, y] = 255
            else:
                pimgGray[x, y] = 0


def blackwhite_inverted(image, black):
    print('[图像处理]正在处理图片: 反色黑白\n')
    width = image.size[0]
    height = image.size[1]
    pimgGray = image.load()
    for y in range(0, height):
        for x in range(0, width):
            if(pimgGray[x, y] > black):
                pimgGray[x, y] = 0
            else:
                pimgGray[x, y] = 255


def blackwhite_cv(file):
    global resizedImage
    i = cv2.imread(file)
    gray = cv2.cvtColor(i, cv2.COLOR_BGR2GRAY)
    blocksize = 31
    C = 1
    binary = cv2.adaptiveThreshold(
        gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blocksize, C)
    cv2.imwrite(file, binary)


def seewo_mode(filename):
    global resizedImage
    print('[图像处理]正在处理图片: 调整大小\n')
    image = Image.open(filename).convert('L')
    width = image.size[0]
    height = image.size[1]
    image = image.crop((0, height * 0.03, width, height * 0.9))
    if(height > width and autoRotate):
        image = image.transpose(Image.ROTATE_90)
        print('[图像处理]正在处理图片: 旋转90度 \n')
    width = image.size[0]
    height = image.size[1]
    n = height/384.0
    w = int(width/n)
    h = int(height/n)
    resizedImage = image.resize((int(w), int(h)))
    blackwhite_inverted(resizedImage, 60)


def procImage(filename, method: str):
    global resizedImage
    try:
        # blackwhite_cv(filename)
        if(method == 'seewo'):
            seewo_mode(filename)
        else:
            size(filename)
        if(method == 'dither'):
            dither(resizedImage)
            blackwhite(resizedImage, 180)
        elif(method == 'bw'):
            blackwhite(resizedImage, 128)
        elif(method == 'bw_inv'):
            blackwhite_inverted(resizedImage, 128)
        else:
            blackwhite(resizedImage, 180)
        resizedImage.save(outimgname)
###############################################################
        print('[信息]转换为hex数据\n')
        buffer = array('B')
        tmpbuffer = 0
        pimgGray = resizedImage.load()
        width = resizedImage.size[0]
        for j in range(0, width):
            for k in range(0, 48):
                for l in range(0, 8):
                    tmpbuffer = tmpbuffer << 1
                    if(pimgGray[j, k*8+l] == 0):
                        tmpbuffer = tmpbuffer + 1
                buffer.append(tmpbuffer & 0xff)
                tmpbuffer = 0
        fout = open(outbinname, 'wb')
        fout.write(buffer)
        fout.close()
    except Exception as e:
        print('[错误]无法处理图片\n')
        print('[错误原因]' + str(e) + '\n')
        return


def procImageBackground(filename, method):
    t2 = threading.Thread(target=procImage, args=(filename, method))
    t2.setDaemon(True)
    t2.start()
    return
